package cn.itcast.hotel;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


@SpringBootTest
public class StartElasticSearch {
    private RestHighLevelClient client;

    @Resource
    private HotelMapper hotelMapper;

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.136.101:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }

    public static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\":{\n" +
            "    \"properties\": {\n" +
            "      \"id\":{\n" +
            "        \"type\": \"long\",\n" +
            "        \"index\":false\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\":\"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\":{\n" +
            "      \"type\": \"text\"\n" +
            "       , \"analyzer\": \"ik_max_word\" \n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\":\"integer\"\n" +
            "      },\n" +
            "      \"score\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"city\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "        , \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"star_name\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      },\n" +
            "      \"location\":{\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\":{\n" +
            "        \"type\":\"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\":{\n" +
            "        \"type\":\"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";

    /**
     * 创建索引库
     */
    @Test
    public void createMapping() throws Exception {
        CreateIndexRequest request = new CreateIndexRequest("hotel1");
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    /**
     * 删除索引库
     */
    @Test
    public void deleteMapping() throws Exception {
        DeleteIndexRequest hotel1 = new DeleteIndexRequest("hotel1");
        client.indices().delete(hotel1, RequestOptions.DEFAULT);
    }

    /**
     * 判断mapper是否存在
     *
     * @throws Exception
     */

    @Test
    public void existsHotel() throws Exception {
        GetIndexRequest indexRequest = new GetIndexRequest("hotel1");
        boolean hotelOne = client.indices().exists(indexRequest, RequestOptions.DEFAULT);
        System.out.println("hotelOne = " + hotelOne);
        GetIndexRequest indexRequest1 = new GetIndexRequest("hotel");
        boolean hotel = client.indices().exists(indexRequest1, RequestOptions.DEFAULT);
        System.out.println("hotel = " + hotel);
    }

    /**
     * 向索引库中添加文档
     */
    @Test
    public void addDocTOIndex() throws Exception {
        IndexRequest hotelRequest = new IndexRequest("hotel").id("1");
        Hotel hotel = hotelMapper.selectById(36934);
        System.out.println(hotel);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        String jsonString = JSON.toJSONString(hotelDoc);
        hotelRequest.source(jsonString, XContentType.JSON);
        client.index(hotelRequest, RequestOptions.DEFAULT);

    }

    /**
     * 查询索引库指定id的文档
     */
    @Test
    public void getDocById() throws Exception {
        GetRequest hotelRequest = new GetRequest("hotel", "1");
        GetResponse response = client.get(hotelRequest, RequestOptions.DEFAULT);
        String sourceAsString = response.getSourceAsString();
        HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
        System.out.println("hotelDoc = " + hotelDoc);
    }

    /**
     * 删除指定id的文档
     */
    @Test
    public void deleteDocById() throws Exception {
        DeleteRequest deleteRequest = new DeleteRequest("hotel", "1");
        client.delete(deleteRequest, RequestOptions.DEFAULT);
    }

    /**
     * 1.全量修改就是先删除再新增;它的api根新增一模一样,因为假如数据存在那么便先删除后修改,
     * 假如数据不存在那么直接新增
     * 2.增量修改;
     */
    @Test
    public void updateDacById() throws Exception {
        UpdateRequest hotelRequest = new UpdateRequest("hotel", "1");
        hotelRequest.doc("price", "952", "startName", "四钻");
        client.update(hotelRequest, RequestOptions.DEFAULT);
    }

    @Test
    public void addBatch() throws Exception {
        List<Hotel> hotels = hotelMapper.selectList(null);
        BulkRequest bulkRequest = new BulkRequest();
      hotels.stream().forEach(
              hotel -> {
                  HotelDoc hotelDoc = new HotelDoc(hotel);
                  String jsonString = JSON.toJSONString(hotelDoc);
                  bulkRequest.add(new IndexRequest("hotel").id(hotel.getId().toString()).source(jsonString,XContentType.JSON));
              }
      );
      client.bulk(bulkRequest,RequestOptions.DEFAULT);

    }


}
